package com.coin900.coin.base.security;

import com.coin900.coin.base.enums.ResponseEnum;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.apache.shiro.web.util.WebUtils;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Unibon
 * <p/>
 * Copyright (c) 2012 YouPeng ValueSoft Inc., All rights reserved.
 * <p/>
 * This software is the confidential and proprietary information of
 * ValueSoft Company. ("Confidential Information").  You shall not
 * disclose such Confidential Information and shall use it only in
 * accordance with the terms of the license agreement you entered into
 * with ValueSoft.com.
 * <p/>
 * Revision History
 * Date      		Programmer       Notes
 * 2014/7/24   	     libo		     Initial
 * *********************************************************************
 */
public class AuthenticationFilter extends FormAuthenticationFilter {
    @Override
    protected void redirectToLogin(ServletRequest request, ServletResponse response) throws IOException {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        String path = httpRequest.getServletPath();
        if (path.lastIndexOf(".json") == -1) {
            String redirect = httpRequest.getServerName();
            String loginUrl = getLoginUrl()+"&redirect=http://"+redirect+path+"?viewType=page";
//            String loginUrl = "http://"+casServer+"?service=http://"+redirect+path+"?viewType=page";
            WebUtils.issueRedirect(request, response, loginUrl, null, false);
        } else {
            response.setContentType("application/json");
            response.setCharacterEncoding("UTF-8");
            try {
                JSONObject data = new JSONObject();
                data.put("stat", ResponseEnum.AUTHC_TIMEOUT);
                Map<String, Object> error = new HashMap<>();
                error.put("field", "error");
                error.put("msg", "权限验证出错");
                List<Map<String, Object>> errors = new ArrayList<>();
                errors.add(error);
                data.put("errors", errors);

                String callback = request.getParameter("callback");
                if(StringUtils.isNotBlank(callback)){
                    response.getWriter().write(callback+"("+data.toString()+")");
                    response.getWriter().flush();
                }else{
                    response.getWriter().write(data.toString());
                    response.getWriter().flush();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        Subject subject = getSubject(request, response);
        if(!subject.isAuthenticated() && subject.isRemembered()){
            Session session = subject.getSession(true);
            if(session.getAttribute("user") == null){
                System.out.println("user==null,");
                String username = subject.getPrincipal().toString();
                Map<String,Object> params = new HashMap<>();
                params.put("username", username);
                System.out.println(username);
                //未登录时
                return false;

            }
        }
        return subject.isAuthenticated() || subject.isRemembered();
    }
}
